<template>
	<view>
		<view class="loading-mask" v-if="loading">
			<text>加载中...</text>
		</view>

	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				loading: false
			};
		},
		computed: {
			...mapState(['data'])
		},
		onLoad() {
			this.createWebviewAndLoadURL();
		},
		methods: {
			// modifyHtml(htmlContent) {
			// 	// 在这里对H5页面的HTML内容进行修改，例如替换文本、添加元素等
			// 	// const modifiedContent = htmlContent.replace('原始文本', '修改后的文本');
			// 	// return modifiedContent;
			// },
			// onMessage(e) {
			// 	// 处理来自 web-view 的消息
			// 	// console.log(e)
			// 	// https://apm.pinduoduo.com/api/cmt/cmtc_h5

			// },
			createWebviewAndLoadURL() {
				// 在 APP-PLUS 平台下执行以下代码
				// #ifdef APP-PLUS
				let loadCount = 0;
				const wv = plus.webview.create("", "custom-webview", {
					plusrequire: "none",
					'uni-app': 'none',
					top: uni.getSystemInfoSync().statusBarHeight + 44,
					bottom: 0
				});

				wv.addEventListener("loaded", () => {
					wv.overrideUrlLoading({
						mode: 'reject'
					}, (e) => {
						console.log('拦截请求：' + e.url);
						if (e.url.includes("com.xunmeng.pinduoduo/index.html")) {
							wv.loadURL("https://mobile.yangkeduo.com/orders.html?type=3");
						}

						if (e.url.includes("mobile.yangkeduo.com/index.html")) {
							uni.request({
								url: e.url,
								method: e.method,
								success: res => {
									uni.showLoading({
										title: '加载中...'
									});
									if (loadCount < 1) { // 限制只重新加载一次
										setTimeout(() => {
											console.log("重新加载页面");
											this.loading = true
											wv.loadURL(
												"https://mobile.yangkeduo.com/orders.html?type=3"
											); // 重新加载同一个URL
											loadCount++; // 增加计数器
										}, 1500)
									} else {
										console.log("已完成重新加载，不再继续");
										// 这里可以执行其他逻辑，比如拦截后续的URL加载等
									}
								},
								fail: err => {
									console.error('请求失败：', err);
								}
							});
						}

						if (e.url.includes("mobile.yangkeduo.com/orders.html")) {
							let newurl = e.url + '&order_index=80'
							uni.request({
								url: newurl,
								method: e.method,
								success: res => {
									this.loading = true
									let obj = {
										datastr: '' 
									}
									let rawData = JSON.stringify(res)
									let pattern = /window\.rawData=(.*?)window\.leo/
									var result = rawData.match(pattern);
									if (result && result.length > 1) {
										let stra = result[1]
										const lastIndex = stra.lastIndexOf(';');
										if (lastIndex !== -1) {
											// str = str.substring(0, lastIndex) + str.substring(lastIndex + 1);
											let strb = stra.substring(0, lastIndex) + stra
												.substring(lastIndex + 1);
											// console.log(strb)
											uni.hideLoading();
											obj.datastr = unescapeString(strb);
											let objdata = JSON.parse(obj.datastr)
											// console.log(objdata)
											if (objdata != null) {
												let dataarr = objdata.ordersStore.orders
												let objdatas = []
												if (dataarr != undefined) {
													dataarr.forEach((item) => {
														let ordergoods = item
															.orderGoods
														ordergoods.forEach((list) => {
															let logisticscompany =
																''
															let orderHintmessage =
																item
																.extraInfo
																.orderHint
																.message
															if (orderHintmessage
																.includes(
																	"商家已发货")
															) {
																const
																	pattern2 =
																	/(?:正在通知)(.*?)(?:取件)/;
																const result2 =
																	orderHintmessage
																	.match(
																		pattern2
																		);

																if (result2 &&
																	result2
																	.length > 1
																	) {
																	logisticscompany
																		=
																		result2[
																			1]
																} else {
																	logisticscompany
																		=
																		item
																		.extraInfo
																		.orderHint
																		.message
																}
															} else if (
																orderHintmessage
																.includes(
																	"运输中") ||
																orderHintmessage
																.includes(
																	"派送中") ||
																orderHintmessage
																.includes(
																	"已签收")
															) {
																// console.log(
																// 	orderHintmessage
																// 	)
																const
																	pattern2 =
																	/\|([^：|]*)：/;
																const result2 =
																	orderHintmessage
																	.match(
																		pattern2
																		);

																if (result2 &&
																	result2
																	.length > 1
																	) {
																	logisticscompany
																		=
																		result2[
																			1]
																		.trim()
																} else {
																	logisticscompany
																		=
																		item
																		.extraInfo
																		.orderHint
																		.message
																}
															}

															let b = {
																order_sn: item
																	.orderSn, //物品单号
																good_name: list
																	.goodsName, //物品名称
																good_price: list
																	.goodsPrice, //物品原来价格
																unit_price: item
																	.orderAmount, //物品实付价格
																good_img: decodeURIComponent(
																	list
																	.thumbUrl
																), //物品图片
																logisticscompany: logisticscompany, //物流公司
																logistics_sn: item
																	.trackingNumber, //物流单号
																good_Items: list
																	.spec, //物品品名
																num: item
																	.goodsNumber //物品数量
															}
															objdatas.push(b)
														})

													});
												}

												let params = {
													user_id: this.data.user.user_id,
													goods: objdatas,
													directUpload: 1,
													type: 3
												}
												// console.log(JSON.stringify(params))
												// console.log(objdatas.length)
												this.loading = false
												uni.hideLoading();
												uni.setStorageSync('paramsdata', JSON
													.stringify(
														params));
												uni.navigateTo({
													url: '/pages/pddimport/pddlist'
												});
												// uni.navigateTo({
												// 	url: `pages/pddimport/pddlist`
												// });
											}

										}

									} else {
										console.log('未找到匹配的数据');
										this.loading = false
									}
								},
								fail: err => {
									console.error('请求失败：', err);
									this.loading = false
								}
							});
						}

					});

				})


				wv.loadURL("https://mobile.yangkeduo.com/login.html");
				setTimeout(function() {
					wv.loadURL("https://mobile.yangkeduo.com/login.html");
				}, 100);
				const currentWebview = this.$scope.$getAppWebview();
				currentWebview.append(wv);

				// 延时一秒后获取 Webview 样式
				setTimeout(function() {
					console.log(wv.getStyle());
				}, 1000);

				function unescapeString(str) {
					return str.replace(/\\n/g, '\n')
						.replace(/\\r/g, '\r')
						.replace(/\\t/g, '\t')
						.replace(/\\b/g, '\b')
						.replace(/\\f/g, '\f')
						.replace(/\\"/g, '"')
						.replace(/\\\\/g, '\\');
				}


				// #endif

			}



		},
		mounted: () => {

		}
	}
</script>

<style>

</style>
